//配置路由
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

/* 已经使用路由懒加载了 */
/*
//引入一级路由
import Home from '@/pages/Home'
import Login from '@/pages/Login'
import Register from '@/pages/Register'
import Search from '@/pages/Search'
import Detail from '@/pages/Detail'
import AddCartSuccess from '@/pages/AddCartSuccess'
import ShopCart from '@/pages/ShopCart'
import Trade from '@/pages/Trade'
import Pay from '@/pages/Pay'
import PaySuccess from '@/pages/PaySuccess'
import Center from '@/pages/Center'

//引入二级路由
import MyOrder from '@/pages/Center/MyOrder'
import GroupOrder from '@/pages/Center/GroupOrder'
*/

//先保存VueRouter原型对象的push和replace
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace

//重写 push
//第一个参数：告诉push方法，要往哪里跳转
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    //call和apply区别
    //相同点：都可以调用函数一次，都可以篡改函数的上下文一次
    //不同点：call和apply传递参数：call传递参数用逗号隔开；apply方法执行，传递数组
    originPush.call(this, location, resolve, reject)
  } else {
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}

//重写 replace
VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject)
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}

let router = new VueRouter({
  routes: [
    {
      //主页
      path: '/home',
      component: () => import('@/pages/Home'),
      meta: {
        show: true
      }
    },
    {
      //搜索页
      path: '/search/:keyword?',
      name: 'search',
      component: () => import('@/pages/Search'),
      meta: {
        show: true
      }
      //路由组件传递props
      // 布尔值写法
      // props: true,
      // 对象写法
      // props: { a: 1, b: 2 }
      // 函数写法
      // props: (route) => {
      //   return { keyword: $route.params.keyword, k: $route.query.keyword }
      // }
    },
    {
      //详情页
      path: '/detail/:skuId',
      name: 'detail',
      component: () => import('@/pages/Detail'),
      meta: {
        show: true
      }
    },
    {
      //添加购物车--成功页面
      path: '/addcartsuccess',
      name: 'addcartsuccess',
      component: () => import('@/pages/AddCartSuccess'),
      meta: {
        show: true
      }
    },
    {
      //购物车页面
      path: '/shopcart',
      name: 'shopCart',
      component: () => import('@/pages/ShopCart'),
      meta: {
        show: true
      }
    },
    {
      //交易页
      path: '/trade',
      name: 'trade',
      component: () => import('@/pages/Trade'),
      meta: {
        show: true
      },
      /**
       * 路由独享守卫
       * 交易页只能从购物车页面进入
       */
      beforeEnter: (to, from, next) => {
        if (from.path == '/shopcart') {
          next()
        } else {
          next(false)
        }
      }
    },
    {
      //支付页
      path: '/pay',
      name: 'pay',
      component: () => import('@/pages/Pay'),
      meta: {
        show: true
      },
      beforeEnter: (to, from, next) => {
        if (from.path == '/trade') {
          next()
        } else {
          next(false)
        }
      }
    },
    {
      //支付成功页
      path: '/paysuccess',
      name: 'paysuccess',
      component: () => import('@/pages/PaySuccess'),
      meta: {
        show: true
      }
    },
    {
      //个人中心
      path: '/center',
      name: 'center',
      component: () => import('@/pages/Center'),
      meta: {
        show: true
      },
      //二级路由组件
      children: [
        {
          path: 'myorder',
          name: 'myOrder',
          component: () => import('@/pages/Center/MyOrder')
        },
        {
          path: 'grouporder',
          name: 'groupOrder',
          component: () => import('@/pages/Center/GroupOrder')
        },
        {
          path: '/center',
          redirect: '/center/myorder'
        }
      ]
    },
    {
      //登录页
      path: '/login',
      component: () => import('@/pages/Login'),
      meta: {
        show: false
      }
    },
    {
      //注册页
      path: '/register',
      component: () => import('@/pages/Register'),
      meta: {
        show: false
      }
    },
    // 重定向
    {
      path: '*',
      redirect: '/home'
    }
  ],
  // vueRouter滚动行为
  scrollBehavior(to, from, savedPosition) {
    // return 期望滚动到哪个的位置
    return { x: 0, y: 0 }
  }
})

/**
 * 全局守卫：前置守卫
 */
router.beforeEach(async (to, from, next) => {
  let token = store.state.user.token
  let name = store.state.user.userInfo.name
  console.log('to', to)
  console.log('from', from)
  if (token) {
    //用户已经登录
    if (to.path == '/login') {
      //登录后不能去login页面，强制跳转到主页
      next('/home')
      console.log('已登录，不能去主页')
    } else {
      //没去登录页，先判断是否有name
      if (name) {
        //有，放行
        next()
        console.log('已登录，有用户信息，放行')
      } else {
        //没有，通过vuex去获取name，然后放行
        try {
          await store.dispatch('getUserInfo')
          console.log('已登录，没有用户信息，发请求拿用户信息，放行')
          next()
        } catch (error) {
          //token失效
          await store.dispatch('userLogout')
          next('/login')
          console.log('token失效，回到登录页')
        }
      }
    }
  } else {
    console.log('未登录')
    //未登录，不能去【个人中心|支付|订单等页面】
    let toPath = to.path
    if (
      toPath.includes('/trade') ||
      toPath.includes('/pay') ||
      toPath.includes('/center')
    ) {
      next('/login?redirect=' + toPath)
    }
    next()
  }
})

export default router
